package cn.security.auth.config;

import cn.security.auth.common.Result;
import cn.security.auth.entity.LoginParam;
import cn.security.auth.service.LoginService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import java.util.HashMap;


public class CustomAuthenticationManagerConfig implements AuthenticationManager {

    private LoginService loginService;

    public void setLoginService(LoginService loginService){
       this.loginService = loginService;
   }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) {
            Result loginResult;
            try {
                  loginResult = loginService.match(new LoginParam(username, password));
                  if (loginResult!=null && loginResult.izSuccess()) {
                      UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username, "N/A", AuthorityUtils.createAuthorityList("ROLE_USER"));
                      HashMap<String,Object> userInfoMap = new HashMap<>();
                      userInfoMap.put("addr","上海");
                      userInfoMap.put("name","赵伟杰");
                      result.setDetails(userInfoMap);
                      SecurityContextHolder.getContext().setAuthentication(result);
                      return result;
                  }
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
